<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="关联用户" prop="userId">
        <el-input
          v-model="selectedUserName"
          placeholder="请选择关联用户"
          clearable
          readonly
          @clear="handleClearUser"
          class="!w-240px"
        >
          <template #suffix>
            <Icon
              icon="ep:search"
              class="cursor-pointer hover:text-primary"
              @click="openUserDialog"
            />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="店铺名称" prop="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入店铺名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="开店时间" prop="openDate">
        <el-date-picker
          v-model="queryParams.openDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="是否营业中" prop="isOpen">
        <el-select
          v-model="queryParams.isOpen"
          placeholder="请选择是否营业中"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.IS_BUSINESS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['direct:store:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['direct:store:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['direct:store:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="门店ID" align="center" prop="id" width="90" />
      <el-table-column label="关联用户" align="center" prop="userName" width="120" />
      <el-table-column label="店铺名称" align="center" prop="storeName" width="150" />
      <el-table-column label="店铺LOGO" align="center" prop="storeLogo" width="100">
        <template #default="scope">
          <el-image
            v-if="scope.row.storeLogo"
            :src="scope.row.storeLogo"
            :preview-src-list="[scope.row.storeLogo]"
            preview-teleported
            class="w-60px h-60px"
            fit="cover"
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="店铺ID/编号" align="center" prop="storeNo" width="140" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" width="120" />
      <el-table-column label="门店地址" align="center" prop="address" width="200" />
      <el-table-column label="经度" align="center" prop="longitude" width="110" />
      <el-table-column label="纬度" align="center" prop="latitude" width="110" />
      <el-table-column label="开店时间" align="center" prop="openDate" width="120" />
      <el-table-column label="营业时间" align="center" prop="businessHours" width="140" />
      <el-table-column label="休息日" align="center" prop="restDay" width="100" />
      <el-table-column label="是否营业中" align="center" prop="isOpen" width="110">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.IS_BUSINESS" :value="scope.row.isOpen" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="所属菜场名称" align="center" prop="marketName" width="140" />
      <el-table-column label="社区菜场名称" align="center" prop="communityMarketName" width="140" /> -->
      <el-table-column label="收银机编号" align="center" prop="cashRegisterNo" width="120" />
      <el-table-column label="粉丝数量" align="center" prop="followerCount" width="90" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.FARM_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180"
      />
      <!-- <el-table-column label="关于我们" align="center" prop="aboutUs" /> -->
      <el-table-column label="操作" align="center" fixed="right" width="200">
        <template #default="scope">
          <el-button link type="primary" @click="openDetail(scope.row.id)"> 查看 </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['direct:store:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['direct:store:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <StoreInfoForm ref="formRef" @success="getList" />

  <!-- 详情弹窗 -->
  <StoreInfoDetail ref="detailRef" />

  <!-- 用户选择弹窗 -->
  <UserSelectDialog ref="userDialogRef" @confirm="handleUserConfirm" />
</template>

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { StoreInfoApi, StoreInfoVO } from '@/api/direct/storeinfo'
import StoreInfoForm from './StoreInfoForm.vue'
import StoreInfoDetail from './StoreInfoDetail.vue'
import UserSelectDialog from './UserSelectDialog.vue'
import type * as UserApi from '@/api/system/user'

/** 自营门店信息 列表 */
defineOptions({ name: 'DirectStoreInfo' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<StoreInfoVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userId: undefined as number | undefined,
  storeName: undefined,
  openDate: [],
  isOpen: undefined as number | undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const userDialogRef = ref() // 用户选择弹窗
const selectedUserName = ref('') // 选中的用户名称

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await StoreInfoApi.getStoreInfoPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  selectedUserName.value = '' // 清空用户名称
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 查看详情操作 */
const detailRef = ref()
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await StoreInfoApi.deleteStoreInfo(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除自营门店信息 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await StoreInfoApi.deleteStoreInfoList(checkedIds.value)
    checkedIds.value = []
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: StoreInfoVO[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await StoreInfoApi.exportStoreInfo(queryParams)
    download.excel(data, '自营门店信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 打开用户选择弹窗 */
const openUserDialog = () => {
  userDialogRef.value?.open()
}

/** 用户选择确认 */
const handleUserConfirm = (user: UserApi.UserVO) => {
  queryParams.userId = user.id
  selectedUserName.value = user.nickname
}

/** 清空用户选择 */
const handleClearUser = () => {
  queryParams.userId = undefined
  selectedUserName.value = ''
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
